<template>
  <el-dialog v-model="dialogValue" title="添加分组" width="600" append-to-body @close="handleClose">
    <el-form ref="elFormRef" :model="form" label-width="auto">
      <el-form-item
        label="分组名称"
        prop="name"
        :rules="{ required: true, message: '请输入分组名称' }"
      >
        <el-input v-model.trim="form.name" placeholder="请输入" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogValue = false">取消</el-button>
        <el-button plain type="primary" @click="submit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref } from 'vue'
import { type FormInstance } from 'element-plus'
import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import emiter from '@renderer/utils/mitt'
import { Group } from 'three'
import { useHistory } from '@renderer/utils/useHistory'

const props = defineProps({
  modelValue: {
    type: Boolean
  },
  check: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits({
  'update:modelValue': (val: boolean) => val
})

const dialogValue = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const form = reactive({
  name: ''
})
const elFormRef = ref<FormInstance>()
function submit() {
  elFormRef.value?.validate((valid) => {
    if (valid) {
      dialogValue.value = false
      addGroup()
    }
  })
}

function handleClose() {
  elFormRef.value?.resetFields()
}
// 将数据变成模型加入场景
const viewportStore = useViewportStore()
const { publicGroup } = storeToRefs(viewportStore)
const { commitHistory } = useHistory()
function addGroup() {
  const group = new Group()
  group.name = form.name
  group.userData.type = 'group'
  publicGroup.value?.add(group)
  nextTick(() => {
    emiter.emit('viewChange')
    commitHistory(`添加分组${form.name}`, 'add')
  })
}
</script>
<style lang="scss" scoped></style>
